package com.itheima.service.mongo.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import com.itheima.domain.mongo.RecommendVideo;
import com.itheima.domain.mongo.Video;
import com.itheima.domain.mongo.Visitor;
import com.itheima.service.mongo.VideoService;
import com.itheima.service.mongo.VisitorService;
import com.itheima.util.ConstantUtil;
import com.itheima.vo.PageBeanVo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;
@DubboService
public class VideoServiceImpl implements VideoService {
    @Autowired
    private MongoTemplate mongoTemplate;
    //分页查询视频
    @Override
    public PageBeanVo findVideoByPage(Long userId, Integer pageNum, Integer pageSize) {
        Query query = Query.query(Criteria.where("userId").is(userId)).with(Sort.by(Sort.Order.desc("date"))).skip((pageNum - 1) * pageSize).limit(pageSize);
        //查询推荐列表
        List<RecommendVideo> recommendVideoList = mongoTemplate.find(query, RecommendVideo.class);
        List<Video> videoList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(recommendVideoList)) {
            for (RecommendVideo recommendVideo : recommendVideoList) {
                // 查询视频详情
                Video video = mongoTemplate.findById(recommendVideo.getVideoId(), Video.class);
                // 添加到集合
                videoList.add(video);

            }
        }
        long total = mongoTemplate.count(query, RecommendVideo.class);
        return new PageBeanVo(pageNum,pageSize,total,videoList);
    }
    @Autowired
    private RedisPidService redisPidService;
 //添加视频
    @Override
    public void saveVideo(Video video) {
        video.setVid(redisPidService.getNextPid(ConstantUtil.VIDEO_ID));
        mongoTemplate.save(video);
        //推荐给自己
        RecommendVideo recommendVideo = new RecommendVideo();

        recommendVideo.setDate(System.currentTimeMillis());
        recommendVideo.setVid(video.getVid());
        recommendVideo.setUserId(video.getUserId());
        recommendVideo.setVideoId(video.getId());
        recommendVideo.setScore(RandomUtil.randomDouble(60, 99));
        mongoTemplate.save(recommendVideo);

    }
    //查询本人视频
    @Override
    public PageBeanVo findVideoByUserId(Long userId, Integer pageNum, Integer pageSize) {
        Query query = Query.query(Criteria.where("userId").is(userId)).with(Sort.by(Sort.Order.desc("created"))).skip((pageNum - 1) * pageSize).limit(pageSize);
        List<Video> videoList = mongoTemplate.find(query, Video.class);
       Long total = mongoTemplate.count(query,Video.class);
        return new PageBeanVo(pageNum,pageSize,total,videoList);
    }
}
